<template>
  <van-popup v-model="isShow" round position="bottom" @close="closePop">
    <div class="deliver_pop">
      <div class="deliver_cont">
        <div class="radio_box">
          <van-checkbox shape="square" icon-size="18px" v-model="isDeliver" @change="changeDeliver">实名投递</van-checkbox>
          <van-checkbox shape="square" icon-size="18px" v-model="isComment"
            @change="changeComment">禁止他人评论</van-checkbox>
        </div>
        <textarea v-model="content" name="" id="" cols="30" rows="10"></textarea>

        <!-- 添加图片 -->
        <div class="img_box" v-if="isShowImg">
          <div class="add_txt">添加图片（限3张）</div>
          <div class="item_img">
            <div v-for="(item, index) in imgArr" :key="index" class="img-container">
              <img :src="item" alt="" :key="index" class="user_img" />
              <img src="@/assets/images/common/close_icon.png" alt="" class="colose_img" @click="delImg" />
            </div>
          </div>
        </div>

        <!-- 添加音频 -->
        <!-- <img src="@/assets/images/home/deliver_play_icon.png" />
        <img src="@/assets/images/home/deliver_pause_icon.png" /> -->
        <div class="music_box" v-if="mp3Url">
          <div class="add_txt">添加音频</div>
          <div class="play_box dis_flex">
            <img src="@/assets/images/home/deliver_play_icon.png" alt="" class="play_icon" @click="playAudio"
              v-if="isPlaying" />
            <img src="@/assets/images/home/deliver_pause_icon.png" alt="" class="play_icon" @click="playAudio" v-else />
            <div class="line"></div>
            <div class="progress_bar">
              <div class="file_bar" :style="{ width: progress + '%' }" />
              <div class="sliding_block" :style="{ left: progress + '%' }" />
            </div>
            <div class="progress_time">{{ formatTime(totalDuration) }}</div>
            <div class="del_txt" @click="delMp3Url">删除</div>
          </div>
        </div>
      </div>
      <!-- 底部 -->
      <div class="footer_box">
        <div class="operation_img">
          <input type="file" ref="fileInput" style="display: none" @change="handleFileUpload" />
          <img src="@/assets/images/function/picture.png" alt="" @click="open(1)" />
          <img src="@/assets/images/function/music.png" alt="" @click="open(2)" />
        </div>
        <div class="footer_btn" @click="toDeliver">投递</div>
      </div>
    </div>

    <!-- 录音弹框 -->
    <recordingPop v-if="isShowRecordingPop" @getMp3Info="getMp3Info" @closeRecordingPop="closeRecordingPop" />
  </van-popup>
</template>

<script>
import recordingPop from "./recordingPop.vue";
import { uploadImg } from "@/api/common.js";
import { getBase64 } from "@/utils/url";
import { deliverFruit } from "@/api/funcation/wisdomTree.js";
export default {
  data() {
    return {
      isShowRecordingPop: false,
      isShow: true,
      isShowImg: false,
      isShowMusic: false,

      checked: true,
      isDeliver: false,
      isComment: false,
      content: "",
      activeIcon: require("@/assets/images/common/checkbox11.png"),
      inactiveIcon: require("@/assets/images/common/checkbox1.png"),
      value: 3,
      checked: true,
      imgArr: [],
      mp3Url: "",
      audioInstance: null,
      progress: 0,
      currentTime: 0,
      duration: 0,
      isPlaying: false,
      totalDuration: 0,//总时长
    };
  },
  components: { recordingPop },
  methods: {
    async getAudioDuration(mp3Url) {
      try {
        const response = await fetch(mp3Url);
        const arrayBuffer = await response.arrayBuffer();
        const audioContext = new AudioContext();
        const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
        this.totalDuration = audioBuffer.duration
        return audioBuffer.duration; // 返回精确时长（秒）
      } catch (err) {
        throw new Error("解析音频失败: " + err.message);
      }
    },
    //拿到音频url
    getMp3Info(val) {
      this.mp3Url = val
      this.isShowRecordingPop = false
      this.audioInstance = new Audio(val);
      this.audioInstance.addEventListener('timeupdate', () => {
        if (this.audioInstance) {
          this.duration = this.audioInstance.duration;
          this.currentTime = this.audioInstance.currentTime;
          this.progress = (this.currentTime / this.duration) * 100;
        }
      });
      this.audioInstance.addEventListener('ended', () => {
        this.isPlaying = false;
      });
      this.getAudioDuration(this.mp3Url)
    },
    //删除图片
    delImg(index) {
      this.imgArr.splice(index, 1);
      if (this.imgArr.length == 0) {
        this.isShowImg = false;
      }
    },
    //上传图片
    async handleFileUpload(event) {
      try {
        const base64 = await getBase64(event.target.files[0]);
        let res = await uploadImg({ file: base64 });
        if (res.code === 200) {
          this.imgArr.push(res.data);
          this.isShowImg = true
          // 重置文件输入框
          this.$refs.fileInput.value = '';
        }
      } catch (error) {
        console.error('文件上传出错:', error);
      }
    },
    //投递
    async toDeliver() {
      let par = {
        type: this.isDeliver ? 0 : 1,
        is_comment: this.isComment ? 1 : 0,
        content: this.content,
        img: this.imgArr,
        file: this.mp3Url
      };
      let res = await deliverFruit(par);
      if (res.code == 200) {
        this.closePop();
        this.$toast.success('投递成功');
      }

    },
    open(val) {
      if (val == 1) {
        if (this.imgArr.length == 3) {
          this.$toast.fail('最多添加3张图片！');
          return
        }
        this.$refs.fileInput.click();
      } else {
        this.isShowRecordingPop = true
      }
    },
    closePop() {
      this.$emit("toColsePop", 2);
    },
    closeRecordingPop() {
      this.isShowRecordingPop = false
    },
    playAudio() {
      if (this.audioInstance && this.mp3Url) {
        if (this.audioInstance.paused) {
          this.audioInstance.play();
          this.isPlaying = true;
        } else {
          this.audioInstance.pause();
          this.isPlaying = false;
        }
      }
    },
    delMp3Url() {
      this.mp3Url = ''
    },
    formatTime(seconds) {
      const minutes = Math.floor(seconds / 60);
      const secs = Math.floor(seconds % 60);
      return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    },
    changeDeliver(e) {
      this.isDeliver = e
    },
    changeComment(e) {
      this.isComment = e
    }
  },
};
</script>

<style scoped lang="less">
::v-deep .van-radio__label {
  font-size: 14px;
  color: #333333;
}

::v-deep .van-radio__icon .van-radio__icon--round .van-radio__icon--checked {
  width: 15.33px;
  height: 15.33px;
}

::v-deep .van-radio-group {
  display: flex;
}

::v-deep .van-radio {
  margin-right: 24.67px;

  &:last-child {
    margin: 0;
  }
}

::v-deep .van-checkbox {
  margin-right: 8px;

  &:last-child {
    margin: 0;
  }

  .van-checkbox__label {
    font-size: 16px;
  }
}

.img-icon {
  width: 15.33px;
  height: 15.33px;
}

.deliver_pop {}

.deliver_cont {
  padding: 29.67px 16.67px 16.67px 16.67px;
}

.radio_box {
  display: flex;
  align-items: center;
}

textarea {
  border: 0;
  width: 100%;
  height: 198px;
  background: #f6f6f6;
  border-radius: 6.67px;
  line-height: 28px;
  font-size: 14px;
  padding: 13px;
  box-sizing: border-box;
  margin-top: 14.33px;
}

.img_box {}

.item_img {
  display: flex;
  margin-top: 19px;
}

.img-container {
  position: relative;
  margin-right: 10px;
}

.item_img .user_img {
  width: 66.67px;
  height: 66.67px;
  border-radius: 6px;
  margin-right: 12px;
}

.item_img .colose_img {
  position: absolute;
  top: -8px;
  right: 8px;
  width: 20.67px;
  height: 20.67px;
}

.add_txt {
  opacity: 0.8;
  font-size: 12px;
  line-height: 24px;
}

//播放
.play_box {
  display: flex;
  align-items: center;
  width: 100%;
  height: 30px;
  background: #f4f6fa;
  border-radius: 6.67px;
  margin: 10px 0 20.33px;
  padding: 0 10px;
}

.play_box .play_icon {
  width: 18px;
  height: 18px;
}

.line {
  width: 0.33px;
  height: 19px;
  opacity: 0.3;
  background: #777777;
  margin: 0 6.67px;
}

.progress_bar {
  position: relative;
  width: 166px;
  height: 6px;
  background: #c2efff;
  border-radius: 3px;
}

.file_bar {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  background: linear-gradient(90deg, #0eaeff 0%, #0eaeff 100%);
  border-radius: 3px;
  transition: width 0.1s linear;
}

.sliding_block {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 10px;
  height: 6px;
  background: linear-gradient(0deg,
      rgba(0, 0, 0, 0.3) 0%,
      rgba(0, 0, 0, 0) 100%),
    #0eaeff;
  border-radius: 4px;
  box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0) inset;
  transition: left 0.1s linear;
}

.progress_time {
  opacity: 0.7;
  font-size: 11.33px;
  color: #333333;
  margin: 0 23px;
}

.del_txt {
  text-align: center;
  color: #555555;
  font-size: 11.33px;
}

.footer_box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 40px;
  padding: 0 14px 0 26px;
  border-top: 0.33px solid #e9e9e9;
}

.operation_img img {
  width: 16.67px;
  height: 16.67px;
  margin-right: 23.33px;

  &:last-child {
    margin: 0;
  }
}

.footer_box .footer_btn {
  width: 60px;
  height: 26.67px;
  line-height: 26.67px;
  background: linear-gradient(0deg, #ffffff -20%, rgba(255, 255, 255, 0) 20%),
    #00aeff;
  border-radius: 13.33px;
  text-align: center;
  color:
    #ffffff;
  font-size: 14px;
}
</style>
